const jwt = require("jsonwebtoken");
const md5 = require("md5");
const { ForbiddenError } = require("../../utils/errors")
const { pathToRegexp } = require("path-to-regexp");

// 认证白名单
const whiteList = [
    {
        path: "/api/admin/login",
        method: ["post"],
    },
    {
        path: "/api/banner",
        method: ["get"]
    },
    {
        path: "/res/captcha",
        method: ["get"]
    },
    {
        path: "/api/blogtype",
        method: ["get"]
    },
    {
        path: "/api/blog/:id",
        method: ["get"]
    },
    {
        path: "/api/blog",
        method: ["get"]
    },
    {
        path: "/api/project",
        method: ["get"]
    },
    {
        path: "/api/setting",
        method: ["get"]
    },
    {
        path: "/api/about",
        method: ["get"]
    },
    {
        path: "/api/message",
        method: ["get", "post"]
    },
    {
        path: "/api/comment",
        method: ["get", "post"]
    }
];

const reg = pathToRegexp(whiteList.map(item => item.path));

module.exports = function (req, res, next) {
    const result = whiteList.filter(item => {
        const reg = pathToRegexp(item.path);

        return reg.test(req.path) && item.method.includes(req.method.toLocaleLowerCase());
    });

    // 进入此if证明不需要验证
    if (result.length) {
        next();
        return;
    }
    // 往下走证明需要验证
    // 但是没有 authorization 字段，证明未登录，直接抛出错误
    if (!req.headers["authorization"]) {
        throw new ForbiddenError("权限不足，请先登录");
    };

    let token = req.headers["authorization"].split(" ")[1]; // 获取请求头中的token

    // 验证token，如果验证失败会自动跳到错误处理中间件，验证成功则正常移交下一个中间件
    const verResult = jwt.verify(token, md5(process.env.JWT_SECURE));
    // 往请求头中添加一个字段
    req.token = {
        id: verResult.id,
        loginId: verResult.loginId,
        name: verResult.name
    }
    next();
}